package com.wman.mvp.http

import com.wman.mvp.base.Constants
import com.wman.mvp.utils.TLog
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @ProjectName: wman
 * @Package: com.wman.mvp.http
 * @ClassName: HttpUtils
 * @Description: java类作用描述
 * @Author: wman
 * @CreateDate: 2020/1/3 10:40
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/1/3 10:40
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
object HttpUtils {
    private var mOkhttp: OkHttpClient? = null

    private fun isTest(isTest: Boolean): String = if (isTest) Constants.BASE_URL_TEST else Constants.BASE_URL

    fun <T> createApi(clazz: Class<T>): T =
            Retrofit.Builder().baseUrl(isTest(true))
                    .client(getClient())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build().create(clazz)

    private fun getClient(): OkHttpClient {
        if (mOkhttp == null) {
            mOkhttp = OkHttpClient.Builder()
                    .addInterceptor(getInterceptor())
                    .retryOnConnectionFailure(true)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .build()
        }
        return mOkhttp as OkHttpClient
    }

    private fun getInterceptor(): Interceptor {
        HttpLoggingInterceptor.Logger {
            TLog.json(it)
        }

        return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
    }

    fun <T> sendHttp(ob: Observable<T>, listener: ResponseListener<T>) {
        ob.subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<T> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: T) {
                        listener.onSuccess(t)
                    }

                    override fun onError(e: Throwable) {
                        listener.onFail(e.message.toString())
                    }
                })
    }

}